<script setup>
import { Edit, Delete } from '@element-plus/icons-vue'
import { onMounted, ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import {
  getAssignmentService,
  addAssignmentService,
  deleteAssignmentService,
  updateAssignmentService,
} from '../../api/assignment'
import { getCourseByTeacherIdService} from '../../api/course'
import { getStuByClassIdService} from '../../api/sc'
import { getByIdAssService} from '../../api/studentAss'

import { useTokenStore } from '../../stores/token'
import { ElMessage,ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { useUserInfoStore } from '../../stores/userInfo'

const userInfoStore = useUserInfoStore()
let data = userInfoStore.userInfo
const userInfo = ref({
  ...data,
})
const router = useRouter()
//课程分类数据模型
const courses = ref([])

const courseId = ref('')
const state = ref('')
const submittedCount = ref(0) //已提交人数
const totalStudents = ref(0)   //总人数

const assignment = ref([])

//分页条数据模型
const pageNum = ref(1) //当前页
const pageSize = ref(10) //每页条数
const total = ref(20) //总条数
//控制抽屉是否显示
const visibleDrawer = ref(false)
//添加表单数据模型
const assignmentModel = ref({
  title: '',
  courseId: '',
  coverImg: '',
  content: '',
  state: '',
})

// 编辑表单是否弹出
const editFormVisible = ref(false)

// 编辑作业按钮绑定数据模型
const editAssingmentForm = ref({
  id: '',
  title: '',
  courseId: '',
  description: '',
  createdAt: '',
  dueDate: '',
  overdue: '',
  isScore:1
})

// 显示课程分类
const getCourse = async () => {
  let res = await getCourseByTeacherIdService(userInfo.value.id)
  courses.value = res.data
}
//添加作业
const addAssignment = async () => {
  let res = await addAssignmentService(assignmentModel.value)
  if (res) {
    ElMessage.success(res.message ? res.message : '添加成功')
    getAssignment()
    visibleDrawer.value = false
  } else {
    ElMessage.error(res.message ? res.message : '很可惜，添加失败了')
  }
}

// 获取作业列表信息
const getAssignment = async () => {
  let pageData = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    courseId: courseId.value ? courseId.value : null,
    state: state.value ? state.value : null,
  };

  // 获取作业数据
  let res = await getAssignmentService(pageData);
  const data = res.data;
  assignment.value = data;

  const AssMap = {};

  // 遍历每个作业，并获取对应的学生提交记录
  for (const item of data) {
    const submissionRecords = await getByIdAssService(item.id); // 获取提交记录
    // 将提交记录存入AssMap并更新当前作业对象的 submittedCount
    AssMap[item.title] = submissionRecords.data.length;
    item.submittedCount = submissionRecords.data.length;
  }
  // 获取所有课程信息并构建映射
  const courseRes = await getCourseByTeacherIdService(userInfo.value.id); // 获取课程数据
  const courseMap = {};
  courseRes.data.forEach(course => {
    courseMap[course.id] = course.name;
  });

  // 根据 courseId 显示课程名称，并获取学生总數
  for (let i = 0; i < assignment.value.length; i++) {
    let assignmentItem = assignment.value[i];
    if (assignmentItem.courseId && courseMap[assignmentItem.courseId]) {
      const students = await getStuByClassIdService(assignmentItem.courseId);
      assignmentItem.totalStudents = students.data.length; // 设置课程总学生数
      assignmentItem.courseName = courseMap[assignmentItem.courseId]; // 设置课程名称
    }
  }
}

// 搜索作业
const selectAssignment = async () => {
  let filteredAssignments = assignment.value;
  // 根据课程ID过滤
  if (courseId.value) {
    filteredAssignments = filteredAssignments.filter(assignment => assignment.courseId === courseId.value);
  }

  // 根据状态过滤
  if (state.value) {
    filteredAssignments = filteredAssignments.filter(assignment => assignment.overdue === Number(state.value));
  }

  assignment.value = filteredAssignments;
}
// 重设下拉框分类信息
const resetCourse = () => {
  courseId.value = ''
  state.value = ''
  getAssignment()
}

// 作业时间信息格式化
const formatDate = (row, column) => {
  // 获取单元格数据
  let data = row[column.property]
  if (data == null) {
    return null
  }
  let dt = new Date(data)
  //   return new Intl.DateTimeFormat()
  return (
    dt.getFullYear() +
    '-' +
    (dt.getMonth() + 1) +
    '-' +
    dt.getDate() +
    ' ' +
    dt.getHours() +
    '点'
  )
}

// 点击显示作业编辑弹框并赋值编辑数据模型
const showEditBox = (row) => {
  editFormVisible.value = true
  editAssingmentForm.value = {...row}
}

// 编辑弹框
const editAssingment = async () => {
  let res = await updateAssignmentService(editAssingmentForm.value)
  ElMessage.success(res.message ? res.message : '修改成功')
  editFormVisible.value = false
  getAssignment()
}
const viewSubmissions = async (assignmentId) => {
  // 跳转到提交页面或弹窗逻辑
  router.push({ path: '/studentAss', query: { assId: assignmentId } }); //携带id查询
}
const showDeleteBox = (row) => {
  ElMessageBox.confirm(
    '您确定要删除吗',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      deleteAssignmentService(row.id)
      await getAssignment()
      ElMessage({
        type: 'success',
        message: '删除成功！',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除取消！',
      })
    })
}
// 刷新时加载
onMounted(() => {
  getAssignment()
  getCourse()
  selectAssignment()
})


</script>
<template>
  <!-- 编辑弹窗 -->
  <el-dialog v-model="editFormVisible" title="编辑作业">
    <el-form :model="editAssingmentForm" label-width='70'>
      <el-form-item label="标题">
        <el-input v-model="editAssingmentForm.title" autocomplete="off" />
      </el-form-item>
      <el-form-item label="截止时间">
        <el-date-picker
        v-model="editAssingmentForm.dueDate"
        type="datetime"
        placeholder="选择日期时间"
         :picker-options="pickerOptions">
    </el-date-picker>
      </el-form-item>
      <el-form-item label="作业内容">
        <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="editAssingmentForm.description">
        </el-input>
      </el-form-item>
      <el-form-item label="状态" style="display: flex; align-items: center;">
        <el-switch
            style="display: block"
            v-model="editAssingmentForm.overdue"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="0"  
            :inactive-value="1"  
            active-text="开放"
            inactive-text="截止">
        </el-switch>
      </el-form-item>
      <el-form-item label="互评阶段" style="display: flex; align-items: center;">
        <el-radio-group v-model="editAssingmentForm.isScore">
        <el-radio-button :label="1">提交阶段</el-radio-button>
        <el-radio-button :label="2">互评阶段</el-radio-button>
        <el-radio-button :label="3">公布成绩</el-radio-button>
      </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editFormVisible = false,ElMessage({message:'编辑已取消'})">取消</el-button>
        <el-button type="primary" @click="editAssingment">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>


  <el-card class="page-container">
    <!-- 卡牌标题 -->
    <template #header>
      <div class="header">
        <span>作业管理</span>
        <div class="extra">
          <el-button type="primary" @click="visibleDrawer = true">发布作业</el-button>
        </div>
      </div>
    </template>

    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item label="课程分类：">
        <el-select placeholder="请选择" v-model="courseId">
          <el-option
            v-for="course in courses"
            :key="course.id"
            :label="course.name"
            :value="course.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="发布状态：">
        <el-select placeholder="请选择" v-model="state">
          <el-option label="开放" value="0"></el-option>
          <el-option label="已截止" value="1"></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="selectAssignment">搜索</el-button>
        <el-button @click="resetCourse()">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 作业列表 -->
    <el-table :data="assignment" style="width: 100%">
      <el-table-column label="序号" width="100" type="index"> </el-table-column>
      <el-table-column label="作业标题" width="150" prop="title">
        <template #default="{ row }">
          <a @click="viewSubmissions(row.id)" style="color: blue; text-decoration: underline; cursor: pointer;">
            {{ row.title }}
          </a>
        </template>
      </el-table-column>
      <el-table-column label="课程" width="150" prop="courseName"></el-table-column>
      <!-- <el-table-column label="作业内容" width="150" prop="description"></el-table-column> -->
      <el-table-column label="提交人数">
        <template #default="{ row }">
          {{row.submittedCount }} / {{ row.totalStudents }}
        </template>
      </el-table-column>
      <el-table-column label="截止时间" prop="dueDate" :formatter="formatDate"></el-table-column>
      <el-table-column label="阶段">
        <template #default="{ row }">
            {{ row.isScore === 1 ? '提交阶段' : (row.isScore === 2 ? '互评阶段' : '公布成绩') }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button :icon="Edit" circle plain type="primary" @click="showEditBox(row)"></el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="showDeleteBox(row)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description=" 没有数据" />
      </template>
    </el-table>
  </el-card>

  <!-- 作业发布或草稿抽屉 -->
  <el-drawer v-model="visibleDrawer" title="发布作业" direction="rtl" size="40%">
    <!-- 添加作业表单 -->
    <el-form :model="assignmentModel" label-width="100px">
      <el-form-item label="作业标题">
        <el-input v-model="assignmentModel.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="选择课程">
        <el-select placeholder="请选择" v-model="assignmentModel.courseId">
          <el-option
            v-for="course in courses"
            :key="course.id"
            :label="course.name"
            :value="course.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="作业内容">
        <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="assignmentModel.description">
        </el-input>
      </el-form-item>
      <el-form-item label="截止时间">
        <div class="block">
          <el-date-picker
            v-model="assignmentModel.dueDate"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addAssignment()">发布</el-button>
        <el-button @click="visibleDrawer = false,ElMessage({message:'已取消'})">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
